package service

import (
	"bufio"
	"context"
	"encoding/json"
	"github.com/gorilla/websocket"
	"github.com/toolkits/pkg/logger"
	coreV1 "k8s.io/api/core/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

func GetPodList(clientSet *kubernetes.Clientset, namespaceName string) (podList *coreV1.PodList, err error) {
	podList, err = clientSet.CoreV1().Pods(namespaceName).List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	return podList, nil
}

func GetPod(clientSet *kubernetes.Clientset, namespaceName, podName string) (podInfo *coreV1.Pod, err error) {
	podInfo, err = clientSet.CoreV1().Pods(namespaceName).Get(context.TODO(), podName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return podInfo, nil
}

func DeletePod(clientSet *kubernetes.Clientset, request DeletePodRequest) (err error) {
	var gracePeriodSeconds *int64
	if request.Immediate == true {
		var second int64 = 0
		gracePeriodSeconds = &second
	}
	err = clientSet.CoreV1().Pods(request.NamespaceName).Delete(context.TODO(), request.PodName, metaV1.DeleteOptions{GracePeriodSeconds: gracePeriodSeconds})
	if err != nil {
		return err
	}
	return nil
}

func GetPodLogs(clientSet *kubernetes.Clientset, namespaceName string, podName string, conn *websocket.Conn) (err error) {
	var logsP *rest.Request
	line := new(int64)
	*line = 100
	logsP = clientSet.CoreV1().Pods(namespaceName).GetLogs(podName, &coreV1.PodLogOptions{Follow: true, TailLines: line})

	podLogStream, err := logsP.Stream(context.TODO())

	scanner := bufio.NewScanner(podLogStream)
	for scanner.Scan() {

		//检查websocket
		if err = conn.WriteMessage(websocket.TextMessage, []byte("OK")); err != nil {
			logger.Error(err)
			return err
		}

		text := scanner.Text()
		b, _ := json.Marshal(text)
		err = conn.WriteMessage(websocket.TextMessage, b)
		if err != nil {
			logger.Infof("写入错误", err)
			continue
		}
	}

	return nil

}
